//
//  SendMessageOperation.m
//  ABlip
//
//  Created by dawid on 09-02-13.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "SendMessageOperation.h"
#import "RegexKitLite.h"
#import "MessageTextField.h"
#import "BlipRequestUpdate.h"
#import "BlipErrors.h"
#import "JSON/JSON.h"

@implementation SendMessageOperation
-(id)initWithLock:(NSLock*)opLock
{
	self = [super init];
	if (self){
		lock = opLock;
	}
	return self;
}
- (void)dealloc {
	
    [super dealloc];
}

- (void)main {
	
	//while ([lock tryLock] == NO){
	//	usleep(10000);
		
	//} 
	
	if ([[AppController shared] hideAfterSendMsg]==YES && [[AppController shared]shortKeyCall]==YES )
		[[AppController shared] hideApp];
	//NSString* authString = [[NSString alloc] initWithFormat:@"%@:%@",userLogin,userPassword];
	BLP_URLRequestUpdate *urlRequest=nil;
	MessageTextField *msgField  = (MessageTextField*)[[AppController shared]textBox];
	
	NSString *textInBox = [NSString stringWithString:[msgField stringValue]];
	if ( [textInBox length] > 0){
		
		NSString *imagePath = nil;
		if ([msgField draggedImagePath] != nil){
			imagePath = [NSString stringWithString:[msgField draggedImagePath]];
		}
		
		NSString *textToSend;
		[[AppController shared] blockTextBox];
		[[AppController shared] stopTimer];
		[[AppController shared] hideRefreshButton];
		
		
		if ([textInBox isMatchedByRegex:@"^[ ]*>{1,2}[^>]+"] == YES){
			//NSString *directedMsgRegex = @"^[ ]*>[ ]*([^ :>]+)[ :]+(.*)$";
			//NSString *privateMsgRegex = @"^[ ]*>>[ ]*([^ :]+)[ :]+(.*)$";
			NSString *directedMsgRegex = @"^[ ]*>[ ]*([^ :>]+)(.*)$";
			NSString *privateMsgRegex = @"^[ ]*>>[ ]*([^ :>]+)(.*)$";
			NSString *recipient = [textInBox stringByMatching:directedMsgRegex capture:1];
			if (recipient!=NULL){
				//urlRequest = [[BLP_URLRequestDirectedMsg alloc] initDirectedMsgWithAuthString:[self userPassword]];
				urlRequest = [[BLP_URLRequestUpdate alloc] initDirectedMsgWithAuthString:[[AppController shared] userPassword]];
				[urlRequest setRecipient:recipient];
				textToSend = [textInBox stringByMatching:directedMsgRegex capture:2];
#ifdef __DEBUG__

				NSLog(@"directedMeesage to:%@ with text:%@",recipient, textToSend);

#endif
				//if (textToSend != NULL)
				//	[urlRequest setMessageText:textToSend];
				
				
			} else{
				recipient = [textInBox stringByMatching:privateMsgRegex capture:1];
#ifdef __DEBUG__

				NSLog(@"privae_message");

#endif
				if (recipient!=NULL){
					//urlRequest = [[BLP_URLRequestDirectedMsg alloc] initPrivateMsgWithAuthString:[self userPassword]];
					urlRequest = [[BLP_URLRequestUpdate alloc] initPrivateMsgWithAuthString:[[AppController shared] userPassword]];
					[urlRequest setRecipient:recipient];
					textToSend = [textInBox stringByMatching:privateMsgRegex capture:2];
					
#ifdef __DEBUG__

					NSLog(@"privateMessage to:%@ withText:%@", recipient, textToSend);

#endif
					if (textToSend !=NULL)
						[urlRequest setMessageText:textToSend];
					
					
				}
			}
		}else {
			urlRequest = [[BLP_URLRequestUpdate alloc] initWithAuthString:[[AppController shared]userPassword]];
			textToSend = textInBox;
		}
		[urlRequest setMessageText:textToSend];
		if(imagePath )
			[urlRequest setPicturePath:imagePath];
		//if ([[msgField attView] imageData]){
//			
//			[urlRequest setImageData:[[msgField attView] imageData]];
//		}
		[urlRequest setBody];
	}
	[[AppController shared] setShortKeyCall: NO];
	//[msgField setDraggedImagePath:@""];
	if (urlRequest!=nil){
		
		NSData *urlData;
		NSURLResponse *responce;
		NSError *error;
		NSURL *urlResp ;
		int tryCount = 1;
		
		while (tryCount >0){
			tryCount--;
			
			urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&responce error:&error];
			if (!urlData){
#ifdef __DEBUG__

				NSLog(@"urlData=nil in sendRequest");

#endif
				
				continue;
			}
			if ([BlipErrors findError:urlData] == YES){
				NSString *dataString = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
				if ([dataString isMatchedByRegex:@"^.{1,3}error.*Nieistniej.*$"] == YES){
					[dataString release];
					dataString = nil;
					[urlResp release];
					urlResp =nil;
					[[AppController shared] performSelectorOnMainThread:@selector(msgRecipientNotExist)
															 withObject:nil
														  waitUntilDone:NO];
					
					return;
				}
				[dataString release];
				dataString = nil;
				continue;
				
			}
			break;
		}
		
		[urlResp release];
		urlResp =nil;
		[urlRequest release];
		urlRequest = nil;
	}
	
	//TODO dorobic obsluge bledow z dataString
	NSData *urlData;
	NSURLResponse *responce;
	NSError *error;
	NSURL *urlResp ;
	BLP_URLRequestUpdate *request = [[BLP_URLRequestUpdate alloc] initGetMethodWithLogin:[[AppController shared]lastUpdateId]:[[AppController shared]userPassword]];
	
	int tryCount = 3;
	
	while (tryCount >0){
		tryCount--;
		
		urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responce error:&error];
		if (!urlData){
#ifdef __DEBUG__

			NSLog(@"urlData=nil in sendRequest");

#endif
			
			continue;
		}
		break;
	}
	
	[urlResp release];
	urlResp =nil;	
	
	
	NSString* respString = [[AppController shared] checkDownloadData:urlData];
	
	if (!respString){
#ifdef __DEBUG__

		NSLog(@"nic w resp");

#endif
		[request release];
		request = nil;
		[[AppController shared] initializeTimer];
		//[[AppController shared] resetTextBox];
		[[AppController shared] unHideRefreshButtton];
		return;
	}
	
	if ([[AppController shared] isFirstRun]==YES && [[AppController shared] hideGrowlNotif] == YES)
		[[AppController shared] sendGrowlDownloadingMsg];

	NSString *userLogin  = [[AppController shared] userLogin];
	
	NSMutableArray* userNames = [[AppController shared] userNames];
	
	if (![[AppController shared] blipMessages]){
#ifdef __DEBUG__

		NSLog(@"tworzenie nowego blip msg");

#endif
		[[AppController shared] createBlipMsg];
	}
	NSMutableArray* blipMessages = [[AppController shared] blipMessages];
	if (respString){
		NSMutableArray *jsonValues = [respString JSONValue];
		
		if (!jsonValues){
#ifdef __DEBUG__

			NSLog(@"jsonValues array is empty!!");

#endif
			[[AppController shared] unHideRefreshButtton];
		}else {
			int i;
			NSString *userName;
			BlipMessage *message;
			for (i =[jsonValues count]-1; i >=0; i--){
				message = [[BlipMessage alloc] initWithJSON:[jsonValues objectAtIndex:i] authorization:[[AppController shared]userPassword]];

				[blipMessages addObject:message];

				userName = [message userName];
				if ([[[message msgType] stringValue] isMatchedByRegex:ABL_REGEX_DELETE_TYPES] == YES){
					if (userName == nil) {
            
          
#ifdef __DEBUG__

						NSLog(@"username = nil");

#endif
					} else if ([userName isEqualToString:userLogin] == YES){
						[message setCanDeleteMessage:YES];
					}
				}
				
				if(userName !=nil && [userNames containsObject:userName]==NO){
					[userNames addObject:userName];
				}
				
				userName = [message recipientName];
				if(userName !=nil && [userNames containsObject:userName]==NO){
					[userNames addObject:userName];
				}
				
				[message release];
				//[message release];
				//message = nil;
				
			}
			
			if ([blipMessages count]>0){
				[[AppController shared] setLastUpdateId:[[blipMessages lastObject] msgId]];
				//		[[[AppController shared] setLastUpdateId:[blipMessages objectAtIndex:[blipMessages count]-1] msgId];
			}
			
			//zapisanie nazw user'ow
			NSMutableArray* temp = [[NSMutableArray alloc] initWithArray:[userNames sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]];
			if (userNames){
				[userNames  release];
				userNames = nil;
			}
			userNames = temp;
			
			int counter =3;
			NSString *path = [[AppController appSupportDir] stringByAppendingPathComponent:BLIP_USERS_PATH];
			while (counter > 0){
				if ([NSKeyedArchiver archiveRootObject:userNames toFile:path] == YES)
					break;
				usleep(1000);
				counter--;
			}
			
		}
		jsonValues = nil;
		
	}
	
	
	
	
#ifdef __DEBUG__

	NSLog(@"lastMsgId:%@", [[AppController shared]lastUpdateId]);

#endif
	[request release];
	request = nil;
#ifdef __DEBUG__

	NSLog(@"blipMsg sendMesOperation =  %d", [blipMessages count]);

#endif
	int counter = 0;
	int moreMsgCount = [blipMessages count] - MAX_GROWL_MSG_IN_OPERATION;
	for (BlipMessage *msg in blipMessages) {
        [msg downloadSynchronousExtendedMsg];
		
		counter++;
		
		if ([[AppController shared] hideGrowlNotif] == YES){
			if ([[AppController shared] isFirstRun] == NO){
				if (counter>MAX_GROWL_MSG_IN_OPERATION){
					if (counter ==MAX_GROWL_MSG_IN_OPERATION+1)
					{
						[[AppController shared] sendGrowlMoreMessages:[NSString stringWithFormat:@"%d", moreMsgCount]];
					}
				}else {
					[[AppController shared] sendGrowlMessage:msg];
					
				}
			}
		}
		
		
    }

	
	
	[[AppController shared] performSelectorOnMainThread:@selector(tryRefreshView:)
											 withObject:@""
										  waitUntilDone:YES];
	
	//[lock unlock];
		
}
@end
